<?php
namespace app\common\model\newmodel;
use think\Model;
use app\common\model\newmodel\Accessories as AccessoryModel;
use app\common\model\newmodel\AccessorySku as AccessorySkuModel;
use app\common\model\newmodel\DeviceAccessory;
use think\Db;
class Device extends Model
{
    protected $table = 'device';
    protected $pk = 'id';
    
    /**
     * 关联工厂
     */
    public function factory()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Factory','factory_id','id');
    }

    /**
     * 不含分页的设备列表
     */
    public static function deviceListMore()
    {
        // 1. 构建查询并获取所有设备数据
        $query = self::with(['factory'])->order('list_order esc');
        
        // 获取所有符合条件的设备，不进行分页
        $items = $query->select();
        $modifiedItems = [];
        
        foreach ($items as $device) {
            $deviceArray = $device->toArray();
            
            // 查询当前设备的所有配件关联信息
            $deviceAccessories = DeviceAccessory::where('device_id', $device->id)
                ->select()
                ->toArray();
                
            $accessories = [];
            foreach ($deviceAccessories as $relation) {
                // 获取配件基本信息
                $accessory = AccessoryModel::find($relation['accessory_id']);
                if (!$accessory) {
                    continue;
                }
                
                $accessoryArray = $accessory->toArray();
                
                // 添加标配/选配标识
                $accessoryArray['is_standard'] = $relation['is_standard'];
                
                // 获取配件规格信息（包含属性值）
                $standards = AccessoryStandard::where('accessory_id', $relation['accessory_id'])
                    ->field('id,accessory_id,standard_name')
                    ->select()
                    ->toArray();
                
                // 为每个规格获取属性值
                foreach ($standards as &$standard) {
                    $standardValues = AccessoryStandardValue::where('standard_id', $standard['id'])
                        ->field('id,standard_id,standard_value')
                        ->select()
                        ->toArray();
                    $standard['values'] = $standardValues;
                }
                
                $accessoryArray['standards'] = $standards;
                // 记录当前配件的规格数量，用于后续排序
                $accessoryArray['standard_count'] = count($standards);
                $accessories[] = $accessoryArray;
            }
            
            // 按规格数量正序排列配件（少的在前，多的在后）
            usort($accessories, function($a, $b) {
                return $a['standard_count'] - $b['standard_count'];
            });
            
            // 移除临时添加的排序字段
            foreach ($accessories as &$acc) {
                unset($acc['standard_count']);
            }
            
            $deviceArray['accessories'] = $accessories;
            $modifiedItems[] = $deviceArray;
        }
        
        return [
            'code' => true,
            'msg' => 'success',
            'data' => $modifiedItems
        ];
    }

    
    /**
     * 设备列表
     */
    public static function DeviceList($page=1, $pageSize=10, $keyword = '', $factory_id = '')
    {
        // 1. 构建查询并获取分页对象
        $query = self::with(['factory'])->order('list_order esc');
        
        if ($factory_id) {
            $query = $query->where('factory_id', $factory_id);
        }
        
        if ($keyword) {
            $query = $query->where('device_name', 'like', "%$keyword%");
        }
        
        $pagination = $query->paginate($pageSize, false, ['page' => $page]);
        $items = $pagination->items(); 
        $modifiedItems = [];
        
        foreach ($items as $device) {
            $deviceArray = $device->toArray();
            
            $deviceAccessories = DeviceAccessory::where('device_id', $device->id)
                ->select()
                ->toArray();
                
            $accessories = [];
            foreach ($deviceAccessories as $relation) {
                $accessory = AccessoryModel::find($relation['accessory_id']);
                if (!$accessory) {
                    continue;
                }
                
                $accessoryArray = $accessory->toArray();
                
                $accessoryArray['is_standard'] = $relation['is_standard'];
                
                $skus = AccessorySkuModel::where('accessory_id', $relation['accessory_id'])->field('id,accessory_id,value')
                    ->select()
                    ->toArray();
                $accessoryArray['skus'] = $skus;
                
                $accessories[] = $accessoryArray;
            }
            
            $deviceArray['accessories'] = $accessories;
            $modifiedItems[] = $deviceArray;
        }
        
        return [
            'code' => 1,
            'msg' => 'success',
            'data' => [
                'items' => $modifiedItems,
                'total' => $pagination->total(),
                'page' => $page,
                'pageSize' => $pageSize,
                'pages' => $pagination->lastPage()
            ]
        ];
    }
    

    /**
     * 添加设备
     */
    public static function addDevice($data)
    {
        if (empty($data['device_name']) || empty($data['factory_id']) || !isset($data['is_need'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }
            $device = new self();
            $device->device_name = $data['device_name'];
            $device->factory_id = $data['factory_id'];
            $device->is_need = $data['is_need'];
            $device->list_order = $data['list_order'];
            
            $device->save();
            if(!empty($data['accessories'])){
                $accessories = $data['accessories'];
                // 启动事务
                Db::startTrans();
                try {
                    foreach($accessories as $accessory){
                        $obj = new DeviceAccessory();
                        $obj->device_id = $device->id;
                        $obj->accessory_id = $accessory['id'];
                        $obj->is_standard = $accessory['is_standard'];
                        // 保存失败会抛出异常
                        $result = $obj->save();
                        if(false === $result){
                            throw new \Exception('配件保存失败: ' . $obj->getError());
                        }
                    }
                    
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    // 可以记录错误日志
                    trace('配件添加事务失败: ' . $e->getMessage(), 'error');
                    return ['code' =>false,'msg'=> '配件添加失败，请重试'];
                }
            }
            return ['code' => 1, 'msg' => '设备添加成功'];
    }
    /**
     * 修改设备
     */
    public static function updateDevice($data)
    {
        if (empty($data['id']) || empty($data['device_name']) || empty($data['factory_id']) || !isset($data['is_need'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }

        $device = self::get($data['id']);
        if (!$device) {
            return ['code' => 0, 'msg' => '设备不存在'];
        }

        try {
            $device->device_name = $data['device_name'];
            $device->factory_id = $data['factory_id'];
            $device->is_need = $data['is_need'];
            $device->list_order = $data['list_order'];
            $device->save();
            $deviceId=$device->id;
            //删除原有的配件信息
            DeviceAccessory::deleteAllDeviceAccessory($deviceId);
            if(!empty($data['accessories'])){
                $accessories = $data['accessories'];
                // 启动事务
                Db::startTrans();
                try {
                    
                    // 插入新的所有的配件信息
                    foreach($accessories as $accessory){
                        $obj = new DeviceAccessory();
                        $obj->device_id = $deviceId;
                        $obj->accessory_id = $accessory['id'];
                        $obj->is_standard = $accessory['is_standard'];
                        // 保存失败会抛出异常
                        $result = $obj->save();
                        if(false === $result){
                            throw new \Exception('配件保存失败: ' . $obj->getError());
                        }
                    }
                    
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    // 可以记录错误日志
                    trace('配件添加事务失败: ' . $e->getMessage(), 'error');
                    return ['code' =>false,'msg'=> '配件添加失败，请重试'];
                }
            }
            return ['code' => 1, 'msg' => '设备修改成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '设备修改失败：' . $e->getMessage()];
        }
    }

    /**
     * 删除设备
     */
    public static function deleteDevice($id)
    {
        if (empty($id)) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }

        $device = self::get($id);
        if (!$device) {
            return ['code' => 0, 'msg' => '设备不存在'];
        }

        try {
            $device_id=$device->id;
            $device->delete();
            return ['code' => 1, 'msg' => '设备删除成功'];
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => '设备删除失败：' . $e->getMessage()];
        }
    }
}